//
//  PPGroupViewController.m
//  pet
//
//  Created by 陈无忌 on 11/13/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPGroupViewController.h"
#import "ChatViewController.h"
#import "PPGroupDetailViewController.h"
#import "PPGroupTableViewCell.h"

#import "PPSystemConfiguraton.h"
#import "supportingHeadFiles.h"
#import "PPGroup.h"
#import "PPConversation.h"
#import "PPCustomBGTableView.h"

@interface PPGroupViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet PPCustomBGTableView *groupTableView;
@property (weak, nonatomic) PPSystemConfiguraton *config;
@property (strong, nonatomic) NSArray *gruopList;

@property (nonatomic, strong) UIRefreshControl *refreshControl; //下拉刷新
@property (nonatomic) BOOL isRefresh;
@property (weak, nonatomic) IBOutlet UISearchBar *groupSearchBar;
@property (nonatomic) BOOL isSearch;

@end

@implementation PPGroupViewController

- (PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [self.groupSearchBar resignFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.groupTableView.delegate = self;
    self.groupTableView.dataSource = self;
    [self getGroup];    
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getGroup) name:@"groupChange" object:nil];
    
    self.isSearch = NO;
    //下拉刷新控件
    self.refreshControl = [[UIRefreshControl alloc] init];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"正在刷新"];
    [self.refreshControl addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
    [self.groupTableView addSubview:self.refreshControl];
    self.isRefresh = NO;
    
    //search bar
    self.groupSearchBar.delegate = self;
//    UITextField *searchBar = [[self.groupSearchBar subviews] lastObject];
    self.groupSearchBar.placeholder = @"输入群组名或群组号搜索";
}

- (void)refreshTableView{
    self.isRefresh = YES;
    [self getGroup];
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.groupTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.groupTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.groupTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.groupTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)getGroup
{
    NSString *url = [PPAPIList getAPIList].PPQueryUserGroupList;
    NSDictionary *params = @{@"userId":@(self.config.userInfo.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *groupDicArray = resultMap[@"groupList"];
            self.gruopList = [PPGroup arrayOfModelsFromDictionaries:groupDicArray];
            for (PPGroup *myGroup in self.gruopList) {
                EMError *err = nil;
                myGroup.group = [[EaseMob sharedInstance].chatManager searchPublicGroupWithGroupId:myGroup.easeMobGroupId error:&err];
            }
            [self.groupTableView reloadData];
            if (self.isRefresh) {
                [self.refreshControl endRefreshing];
                self.isRefresh = NO;
            }
        }else{
            [PPHUD hudShowWithString:@"获取群聊列表失败" andView:self.view];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
    }];
}


#pragma mark - UISearch bar delegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    //开始编辑 取消按钮出现
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    self.isSearch = YES;
    [HUD showUIBlockingIndicatorWithText:@"正在搜索"];
    NSString *url = [PPAPIList getAPIList].PPSearchGroup;
    NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"keyword":searchBar.text};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *groupDicArray = resultMap[@"groupList"];
            self.gruopList = [PPGroup arrayOfModelsFromDictionaries:groupDicArray];
            for (PPGroup *myGroup in self.gruopList) {
                EMError *err = nil;
                myGroup.group = [[EaseMob sharedInstance].chatManager searchPublicGroupWithGroupId:myGroup.easeMobGroupId error:&err];
            }
            [self.groupTableView reloadData];
        }else{
            [PPHUD hudShowWithString:@"搜索失败" andView:self.view];
        }
        [HUD hideUIBlockingIndicator];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [HUD hideUIBlockingIndicator];
        [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
    }];
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    self.isSearch = NO;
    //取消搜索，显示自己的群组列表
    [searchBar resignFirstResponder];
    searchBar.text = @"";
    [searchBar setShowsCancelButton:NO animated:YES];
    [self getGroup];
}

#pragma mark - UITableView datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.gruopList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPGroupTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"groupCell"];
    PPGroup *group = [self.gruopList objectAtIndex:indexPath.row];
    cell.groupLabel.text = [NSString stringWithFormat:@"%@(%@)",group.groupName,group.easeMobGroupId];
    return cell;
}

#pragma mark - UITableView delegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PPGroup *group = [self.gruopList objectAtIndex:indexPath.row];
    if (self.isSearch) {
        PPGroupDetailViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPGroupDetailViewController"];
        targetVC.group = group;
        [self.navigationController pushViewController:targetVC animated:YES];
    }else{
        NSString *url = [PPAPIList getAPIList].PPQueryConversationByTargetId;
        NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"targetId":group.easeMobGroupId};
        [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSNumber *processResult = responseObject[@"processResult"];
            if (processResult.boolValue) {
                NSDictionary *resultMap = responseObject[@"resultMap"];
                NSDictionary *conversationDic = resultMap[@"conversation"];
                NSError *err = nil;
                PPConversation *groupConversation = [[PPConversation alloc] initWithDictionary:conversationDic error:&err];
                ChatViewController *targetVC = [[ChatViewController alloc] initWithGroup:group.group];
                targetVC.myConversation = groupConversation;
                targetVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:targetVC animated:YES];
            }else{
                [PPHUD hudShowWithString:@"没有获取到会话" andView:self.view];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
        }];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
